﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zhongchouwwwww.Models;

namespace Zhongchouwwwww.webform
{
    public partial class project_returns_set : System.Web.UI.Page
    {
        public string Namesssss = null;
        public static bool result = true;
        //private static Returnsetinfo returnsetinfo ;
        private static int ProjectID = 0;
        public static bool IsTrue = true;
        public static List<string> names = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //登录验证
                if (!BAL.DataVerification.IsSignin())
                    Response.Redirect("user-login.aspx");

                string ider = Request.QueryString["id"];
                string num = Request.QueryString["num"];
                if (ider == null)//验证是否由上一个页面跳转
                {
                    Response.Redirect("project-add_item1.aspx");
                }
                else
                {
                    Response.Write("<script>alert('添加基本项目信息成功')</script>");
                }
                if (num==null)
                {
                    //获取上一页面的项目实例对象
                    string sqllll = $"select * from Projectinfo where projectname ='{Config.Config.projectname}' and state = '草稿'";
                    var Projects = BAL.GetDate.db.Database.SqlQuery<Projectinfo>(sqllll).First();
                    //取得项目id
                    ProjectID = Projects.projectid;
                    Config.Config.TempProjectID = Projects.projectid;
                }
                else
                {
                    Config.Config.TempProjectID = int.Parse(num);
                    ProjectID = int.Parse(num);
                }

            }
           
            //回报表
            DateShow();
        }

        private void DateShow()
        {
            GrVws.DataSource = null;
            //添加项目的回报表具体内容
            GrVws.DataSource = GetThisProjectReturnset();
            GrVws.DataBind();
        }

        public static List<ReturnsetinfoDTO> GetThisProjectReturnset()
        {
            List<ReturnsetinfoDTO> dates = new List<ReturnsetinfoDTO>();
            using (ZhongchouDBEntities db = new ZhongchouDBEntities())
            {
               var datess = db.Database.SqlQuery<Returnsetinfo>($"select * from Returnsetinfo where projectid = {ProjectID}").ToList();
                for (int i = 0; i < datess.Count(); i++)
                {
                    dates.Add(数据转换(datess[i], i));
                }
            }
            
            return dates;
        }

        public static ReturnsetinfoDTO 数据转换(Returnsetinfo item,int Noo)
        {
        
            return new ReturnsetinfoDTO()
            {
                freight = item.freight =="0"? "包邮": item.freight+"元",
                timess = "项目结束"+item.time+"天后",
                returncontent = item.returncontent,
                jine = item.supportmoney,
                No = Noo+1,
                numbers= item.number == 0? "不限名额": item.number+"位"
            };
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            if (result)
            {
                btnShow.Text = "收起";
                PanHide.Visible = true;
                result = false;
            }
            else
            {
                btnShow.Text = "添加";
                PanHide.Visible = false;
                result = true;
            }
        }
        private static bool Insert(ZhongchouDBEntities db, Returnsetinfo returnsetinfo)
        {
            try
            {
                db.Returnsetinfo.Add(returnsetinfo);
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            
        }


        /// <summary>
        /// 保存回报按钮   添加回报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnbc_Click(object sender, EventArgs e)
        {
            using (ZhongchouDBEntities db = new ZhongchouDBEntities())
            {
                Returnsetinfo returnsetinfo = new Returnsetinfo
                {
                    supportmoney = int.Parse(txtmoney.Text),
                    returncontent = txtcontetion.Text,
                    //txtunlimited
                    number = int.Parse(txtunlimited.Text),
                    freight = txtyf.Text,
                    time = int.Parse(txtday.Text),
                    projectid = ProjectID
                };
                if (Insert(db,returnsetinfo))
                {
                    btnShow.Text = "添加";
                    PanHide.Visible = false;
                    result = true;
                    txtmoney.Text = "";
                    txtcontetion.Text = "";
                    txtunlimited.Text = "";
                    txtyf.Text = "";
                    txtday.Text = "";
                    txtday.Text = "";
                    Response.Write("<script>alert('添加成功')</script>");
                }
                else
                {
                    Response.Write("<script>alert('添加失败')</script>");
                }
            }


        }

        /// <summary>
        /// 保存图片至项目文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImage_Click(object sender, EventArgs e)
        {
            bool ImgIsTrue = true;
            names.Clear();
            if (this.FlUpimg.HasFile)
            {
                this.laMessage.Text = "";
                IList<HttpPostedFile> fileNames = FlUpimg.PostedFiles;
                int SJS = new Random().Next(0, 10000);
                if (fileNames.Count == 3)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        string fileName = fileNames[i].FileName;
                        string fileFexx = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
                        if (fileFexx != "jpg" && fileFexx != "png" && fileFexx != "jpeg" && fileFexx != "gif")
                        {
                            ImgIsTrue = false;
                            break;
                        }
                        else
                        {
                            ImgIsTrue = true;
                            names.Add("../images/" + SJS + Config.Config.ThisUser.UserId + fileNames[i].FileName);
                        }
                    }
                    if (ImgIsTrue)
                    {
                        for (int i = 0; i < fileNames.Count; i++)
                        {
                            FlUpimg.SaveAs(Server.MapPath("..") + "/images/" + names[i]);
                            this.laMessage.Text += fileNames[i].FileName + "**";
                        }
                        Response.Write("<script>alert('项目图片上传成功！如需更改可以再次上传！')</script>");
                        IsTrue = true;
                    }
                    else
                    {
                        Response.Write("<script>alert('上传的文件不是图片类型，请重新上传')</script>");
                        IsTrue = false;
                    }
                    
                }
                else
                {
                    Response.Write("<script>alert('超出上传文件数量或未达到三张图片')</script>");
                    IsTrue = false;
                }
            }
            else
            {
                this.laMessage.Text = "您还没有选择图片";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static (bool 是否成功,string 失败原因) InsertImg()
        {
            string Namesssss = "";
            if (IsTrue)
            {
                try
                {
                    Namesssss = names[0] + "?" + names[1] + "?" + names[2];
                    string sql = $"update Projectinfo set showimgurl='{Namesssss}' where projectname='{Config.Config.projectname}'and userid='{Config.Config.ThisUser.UserId}'";
                    BAL.GetDate.EXEXE(sql);
                    return (true, "");
                }
                catch (Exception)
                {
                    return (false, "项目说明图片必须上传");
                }  
            }
            else
            {
                return  (false,"");
            }
        }

        public static bool HaveDate()
        {
           return BAL.GetDate.db.Database.SqlQuery<Returnsetinfo>($"select * from Returnsetinfo where projectid = {ProjectID}").ToList().Count>=1? true:false;
        }

        protected void nextstep_Click(object sender, EventArgs e)
        {
            bool GOtoNet = true;
            var (是否成功, 失败原因) = InsertImg();
            //图片上传成功+数据库更新数据成功 
            if (是否成功)
            {
                GOtoNet = true;
            }
            else
            {
                GOtoNet = false;
                Response.Write($"<script>alert('{失败原因}')</script>");
            }
            //回报至少写一项后 页面跳转
            if (GOtoNet && HaveDate())
            {

                if (BAL.GetDate.db.Database.ExecuteSqlCommand($"update Projectinfo set prostate = '2' where projectid='{ProjectID}'") > 0)
                {
                    Response.Redirect("project-initiator-mesg.aspx?id=1");
                    return;
                }
                Response.Write("<script>alert('回报至少添加一项')</script>");
                return;
            }
            else
            {
                Response.Write("<script>alert('回报至少添加一项')</script>");
            }

        }

        protected void btnqx_Click(object sender, EventArgs e)
        {
            btnShow.Text = "添加";
            PanHide.Visible = false;
            result = true;
            txtmoney.Text = "";
            txtcontetion.Text = "";
            txtunlimited.Text = "";
            txtyf.Text = "";
            txtday.Text = "";
            txtday.Text = "";
        }
    }
}